<template>
  <div class='paper-dialog'>
    <el-dialog title="试卷编辑" top="10px" class="large_dialog" :visible.sync="dialogVisible" :close-on-click-modal="false">
      <el-form ref="form" :model="formData" :rules="rules" label-width="160px" size="small">
        <custom-title title="基本信息" />
        <el-form-item label="试卷名称:" prop="examPaperName">
          <el-input v-model="formData.examPaperName" />
        </el-form-item>
        <el-form-item label="考试说明:" prop="remark">
          <el-input type="textarea" :rows="3" placeholder="请输入备注" v-model="formData.remark" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="考试限时（分钟）:" prop="examDuration">
              <el-input v-model="formData.examDuration" type="number" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="通过分数:" prop="examPassScore">
              <el-input v-model="formData.examPassScore" type="number" />
            </el-form-item>
          </el-col>
        </el-row>
        <custom-title title="选择题">
          <template #utils>
            <el-button class="btn_primary" @click="questionSelect('choice')">题目选择</el-button>
          </template>
        </custom-title>
        <base-table height="170" hasIndex :tableModel="choiceList" :tableItemConfig="choiceTableConfig" :operationOptions="operationOptions" @handleDelete="(row,type)=> this.handleDelete(row,'0')">
          <template v-slot:questionInfo="{ scope,item }">
            {{ combineString(scope.row[item.prop]) }}
          </template>
        </base-table>
        <custom-title title="判断题">
          <template #utils>
            <el-button class="btn_primary" @click="questionSelect('trueOrFalse')">题目选择</el-button>
          </template>
        </custom-title>
        <base-table height="170" hasIndex :tableModel="trueOrFalseList" :tableItemConfig="trueOrFalseTableConfig" :operationOptions="operationOptions" @handleDelete="(row,type)=> this.handleDelete(row,'1')">
        </base-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" class="btn_cancel">取 消</el-button>
        <el-button @click="submitForm" type="primary" class="btn_primary">确 认</el-button>
      </div>
    </el-dialog>
    <QuestionSelectDialog ref="questionSelectDialog" @questionChange="(question,type) => this.questionChange(question,type)"></QuestionSelectDialog>
  </div>
</template>

<script>
import QuestionSelectDialog from './QuestionDialog'
import { updateExamPaper, addExamPaper } from '@/api/examination'
export default {
  data () {
    return {
      dialogVisible: false,
      // 考试资料数据
      formData: {},
      // 试卷表单验证规则
      rules: {
        examPaperName: [{ required: true, message: '请输入试卷名称', trigger: 'blur' }],
        examPassScore: [{ required: true, message: '请输入通过分数', trigger: 'blur' },],
        examDuration: [{ required: true, message: '请输入考试限时（分钟）', trigger: 'blur' },],
      },
      // 选择题表格配置
      choiceTableConfig: [
        {
          label: '题目',
          prop: 'examQuestionContent'
        },
        {
          label: '选项',
          prop: 'questionItemInfo',
          slotName: 'questionInfo'
        },
        {
          label: '分数',
          prop: 'score'
        }
      ],
      operationOptions: {
        canDelete: true,
        details: false
      },
      // 判断题表格配置
      trueOrFalseTableConfig: [
        {
          label: '题目',
          prop: 'examQuestionContent'
        },
        {
          label: '分数',
          prop: 'score'
        }
      ],
      // 选择题列表数据
      choiceList: [],
      // 判断题列表数据
      trueOrFalseList: [],
      // 总条数
      total: ''
    };
  },
  computed: {},
  watch: {},
  created () {

  },
  mounted () {

  },
  methods: {
    show (data) {
      this.dialogVisible = true
      this.resetForm()
      if (data !== undefined) {
        const paperQuestionList = data.examPaperQuestionList
        if (paperQuestionList.length > 0) {
          this.choiceList = this.filterQuestion(paperQuestionList, '0')
          this.trueOrFalseList = this.filterQuestion(paperQuestionList, '1')
        }
        this.$nextTick(()=>{
          this.formData = JSON.parse(JSON.stringify(data))
        })
      }
    },
    // 根据类型过滤题型
    filterQuestion (data, type) {
      const result = data.filter(item => item.questionType === type).map(item => { return { ...item, score: 2 } })
      return result
    },
    // 数组转字符串
    combineString (arr) {
      const answerItem = arr.map(item => `${item.itemName}: ${item.itemValue}`)
      const result = answerItem.join(' ')
      return result
    },
    // 点击题目选择
    async questionSelect (type) {
      const questionType = type === 'choice' ? '0' : '1'
      this.$refs.questionSelectDialog.show(questionType)
    },
    questionChange (question, type) {
      this.selectQuestion(question, type)
    },
    // 选中题目后处理
    selectQuestion (question, type) {
      switch (type) {
        case '0':
          this.choiceList = this.addNoRepeatQuestion(question, this.choiceList)
          break
        case '1':
          this.trueOrFalseList = this.addNoRepeatQuestion(question, this.trueOrFalseList)
          break
      }
    },
    // 添加不重复题
    addNoRepeatQuestion (targetArray, sourceArray) {
      const targetSet = new Set(targetArray.map(item => item.examQuestionId));
      const newValues = sourceArray.filter(value => !targetSet.has(value.examQuestionId));
      const resultValues = targetArray.concat(newValues).map(item => { return { ...item, score: 2 } })
      return resultValues
    },
    // 清空formData 
    resetForm () {
      this.formData = {
        pageNum: 1, // 当前页
        pageSize: 10,  // 默认条数 
        examDuration: 0,
        examPaperName: '',
        // examPaperQuestionList: [],
        examPassScore: 0,
        remark: undefined
      }
      this.choiceList = []
      this.trueOrFalseList = []
      this.$nextTick(() => {
        this.$refs.form.resetFields()
      })
    },
    // 提交Form表单
    async submitForm () {
      try {
        const isAddOperation = this.formData.examPaperId === undefined
        const method = isAddOperation ? addExamPaper : updateExamPaper
        const message = isAddOperation ? '新增成功' : '修改成功'
        this.formData.examPaperQuestionList = this.choiceList.concat(this.trueOrFalseList)
        const response = await method(this.formData)
        if (response.code === 200) {
          this.dialogVisible = false
          this.$message.success(message)
          this.$emit('replace')
        }
      }
      catch (error) {
        this.$message.error('操作失败')
      }
    },
    // 题目点击删除
    handleDelete (data, type) {
      switch (type) {
        case '0':
          this.choiceList = this.choiceList.filter(item=> item.examPaperQuestionId !== data.examPaperQuestionId)
          break
        case '1':
          this.trueOrFalseList = this.trueOrFalseList.filter(item=> item.examPaperQuestionId !== data.examPaperQuestionId)
          break
      }
    }
  },

  components: {
    QuestionSelectDialog
  },
}
</script>

<style lang='less' scoped>
</style>